package cn.lbd;

import org.junit.Test;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Pipe;

public class TestPipe {
    @Test
    public void test1() {
        Pipe.SinkChannel sinkChannel = null;
        Pipe.SourceChannel sourceChannel = null;
        try {
            Pipe pipe = Pipe.open();
            sinkChannel = pipe.sink();
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            byteBuffer.put("测试文本...".getBytes());
            byteBuffer.flip();
            sinkChannel.write(byteBuffer);

            sourceChannel = pipe.source();
            byteBuffer.flip();
            int len = sourceChannel.read(byteBuffer);
            System.out.println(new String(byteBuffer.array(), 0, len));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (sinkChannel != null) {
                    sinkChannel.close();
                }
                if (sourceChannel != null) {
                    sourceChannel.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
